/*
 * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */
package java.util.stream;

import java.util.*;
import java.util.function.*;

/**
 * 支持顺序和并行聚合操作的一系列元素。 以下示例说明了使用Stream和IntStream的汇总操作 ：
 * int sum = widgets.stream() .filter(w -> w.getColor() == RED) .mapToInt(w -> w.getWeight()) .sum();
 * 在这个例子中， widgets是Collection<Widget> 。
 * 我们通过Collection.stream()创建一个Widget对象的流，过滤它以产生仅包含红色小部件的流，然后将其转换为表示每个红色小部件的权重的int值。 然后将该流相加以产生总重量。
 *
 * 除了Stream ，其为对象引用的流，存在原语特为IntStream ， LongStream和DoubleStream ，所有这些都称为“流”和符合此处描述的特征和限制。
 * @param <T> the type of the stream elements
 * @since 1.8
 * @see IntStream
 * @see LongStream
 * @see DoubleStream
 * @see <a href="package-summary.html">java.util.stream</a>
 */
public interface Stream<T> extends BaseStream<T, Stream<T>> {

    /**
     * 返回由与此给定谓词匹配的此流的元素组成的流。
     * @param predicate 一个 non-interfering ， stateless谓词应用到每个元素，以确定是否它应包含
     * @return 新的流
     */
    Stream<T> filter(Predicate<? super T> predicate);

    /**
     * 返回由给定函数应用于此流的元素的结果组成的流。
     * @param <R> 新流的元素类型
     * @return 一个 non-interfering ， stateless函数应用到每个元件
     */
    <R> Stream<R> map(Function<? super T, ? extends R> mapper);






    /**
     * 返回一个IntStream ，其中包含将给定函数应用于此流的元素的结果。
     * @param mapper -一个 non-interfering ， stateless函数应用到每个元件
     * @return 新的流
     */
    IntStream mapToInt(ToIntFunction<? super T> mapper);

    /**
     * 返回一个LongStream ，其中包含将给定函数应用于此流的元素的结果。
     * @param mapper 一个 non-interfering ， stateless函数应用到每个元件
     * @return 新的流
     */
    LongStream mapToLong(ToLongFunction<? super T> mapper);

    /**
     * 返回一个DoubleStream ，其中包含将给定函数应用于此流的元素的结果。
     * @param mapper 一个 non-interfering ， stateless函数应用到每个元件
     * @return 新的流
     */
    DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper);







    /**
     * 遍历集合下面的集合
     * 返回由通过将提供的映射函数应用于每个元素而产生的映射流的内容来替换该流的每个元素的结果的流。
     * 每个映射的流在其内容被放入此流之后是closed 。（如果映射的流是null则使用空的流）。
     * flatMap()操作具有对流的元素应用一对多变换，然后将所得到的元素平坦化为新流的效果。
     * 传递给flatMap的mapper函数将一行（使用简单的正则表达式）分割成一个单词数组，然后从该数组中创建一个单词。
     * @param <R> 新流的元素类型
     * @param mapper 一个 non-interfering ， stateless功能应用到其产生新的值的流的每个元素
     * @return 新的流
     */
    <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);

    /**
     * @see #flatMap(Function)
     */
    IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper);

    /**
     * @see #flatMap(Function)
     */
    LongStream flatMapToLong(Function<? super T, ? extends LongStream> mapper);

    /**
     * @see #flatMap(Function)
     */
    DoubleStream flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper);




    /**
     * 返回由该流的不同元素（根据Object.equals(Object) ）组成的流。
     * 对于有序流，选择不同的元素是稳定的（对于重复的元素，首先在遇到顺序中出现的元素被保留。）对于无序流，不能保证稳定性。
     *
     * 保存稳定性为distinct()在并行管线是相对昂贵的（要求操作充当一个完整屏障，具有大量缓冲的开销）通常不需要的，和稳定性。
     * 使用无序流源（如generate(Supplier) ）或具有除去排序约束BaseStream.unordered()可导致显著更高效的执行为distinct()在并行管线，如果情况许可的语义。
     * 如果需要与遇到顺序一致， distinct()在并行流水线中使用distinct()您的性能或内存利用率不佳，则使用BaseStream.sequential()切换到顺序执行可能会提高性能。
     * @return 新的流
     */
    Stream<T> distinct();

    /**
     * 返回由该流的元素组成的流，根据提供的Comparator进行排序。
     * 对于有序流，排序稳定。 对于无序的流，不能保证稳定性
     * @return 新的流
     */
    Stream<T> sorted();

    Stream<T> sorted(Comparator<? super T> comparator);

    /**
     * 返回由该流的元素组成的流，另外在从生成的流中消耗元素时对每个元素执行提供的操作。
     *     Stream.of("one", "two", "three", "four")
     *         .filter(e -> e.length() > 3)
     *         .peek(e -> System.out.println("Filtered value: " + e))
     *         .map(String::toUpperCase)
     *         .peek(e -> System.out.println("Mapped value: " + e))
     *         .collect(Collectors.toList());
     *  对于并行流管线，可以在上游操作的任何时间和任何线程中调用该元素可用的动作。 如果操作修改共享状态，则负责提供所需的同步。
     * @return 新的流
     */
    Stream<T> peek(Consumer<? super T> action);

    /**
     * 返回由该流的元素组成的流，截断长度不能超过maxSize 。
     * @param maxSize the number of elements the stream should be limited to
     * @return the new stream
     * @throws IllegalArgumentException if {@code maxSize} is negative
     */
    Stream<T> limit(long maxSize);

    /**
     * 在丢弃流的第一个n元素后，返回由该流的n元素组成的流。 如果此流包含少于n元素，那么将返回一个空流。
     * @param n the number of leading elements to skip
     * @return the new stream
     * @throws IllegalArgumentException 如果 n为负数
     */
    Stream<T> skip(long n);

    /**
     * 对此流的每个元素执行操作。
     * 这个操作的行为显然是不确定的。 对于并行流管道，此操作不保证遵守流的遇到顺序，因为这样做将牺牲并行性的好处。
     * 对于任何给定的元素，动作可以在图书馆选择的任何时间和任何线索中执行。 如果操作访问共享状态，则负责提供所需的同步。
     * @param action 一个 non-interfering对元素执行的动作
     */
    void forEach(Consumer<? super T> action);

    /**
     * 如果流具有定义的遇到顺序，则以流的遇到顺序对该流的每个元素执行操作。
     * 此操作一次处理元素，如果存在，则按照遇到的顺序进行处理。
     * 执行一个元素happens-before执行后续元素的操作的操作，但对于任何给定的元素，该操作可以在库选择的任何线程中执行。
     * @param action 一个 non-interfering对元素执行的动作
     * @see #forEach(Consumer)
     */
    void forEachOrdered(Consumer<? super T> action);

    /**
     * 返回一个包含此流的元素的数组。
     */
    Object[] toArray();

    /**
     * 使用提供的generator函数返回包含此流的元素的数组，以分配返回的数组，以及分区执行或调整大小可能需要的任何其他数组。
     * 发生器函数采用一个整数，它是所需数组的大小，并产生一个所需大小的数组。 这可以用数组构造函数引用简明扼要地表达：
     * Person[] men = people.stream().filter(p -> p.getGender() == MALE) .toArray(Person[]::new);
     * @param <A>        结果数组的元素类型
     * @param generator  产生所需类型和所提供长度的新数组的函数
     * @return 一个包含此流中的元素的数组
     * @throws ArrayStoreException 如果从数组生成器返回的数组的运行时类型不是此流中每个元素的运行时类型的超类型
     */
    <A> A[] toArray(IntFunction<A[]> generator);


    T reduce(T identity, BinaryOperator<T> accumulator);

    /**
     *
     * @param accumulator an <a href="package-summary.html#Associativity">associative</a>,
     *                    <a href="package-summary.html#NonInterference">non-interfering</a>,
     *                    <a href="package-summary.html#Statelessness">stateless</a>
     *                    function for combining two values
     * @return an {@link Optional} describing the result of the reduction
     * @throws NullPointerException if the result of the reduction is null
     * @see #reduce(Object, BinaryOperator)
     * @see #min(Comparator)
     * @see #max(Comparator)
     */
    Optional<T> reduce(BinaryOperator<T> accumulator);

    /**
     * @param <U> The type of the result
     * @param identity the identity value for the combiner function
     * @param accumulator an <a href="package-summary.html#Associativity">associative</a>,
     *                    <a href="package-summary.html#NonInterference">non-interfering</a>,
     *                    <a href="package-summary.html#Statelessness">stateless</a>
     *                    function for incorporating an additional element into a result
     * @param combiner an <a href="package-summary.html#Associativity">associative</a>,
     *                    <a href="package-summary.html#NonInterference">non-interfering</a>,
     *                    <a href="package-summary.html#Statelessness">stateless</a>
     *                    function for combining two values, which must be
     *                    compatible with the accumulator function
     * @return the result of the reduction
     * @see #reduce(BinaryOperator)
     * @see #reduce(Object, BinaryOperator)
     */
    <U> U reduce(U identity,
                 BiFunction<U, ? super T, U> accumulator,
                 BinaryOperator<U> combiner);


    /**
     * Performs a <a href="package-summary.html#MutableReduction">mutable
     * reduction</a> operation on the elements of this stream.  A mutable
     * reduction is one in which the reduced value is a mutable result container,
     * such as an {@code ArrayList}, and elements are incorporated by updating
     * the state of the result rather than by replacing the result.  This
     * produces a result equivalent to:
     * <pre>{@code
     *     R result = supplier.get();
     *     for (T element : this stream)
     *         accumulator.accept(result, element);
     *     return result;
     * }</pre>
     *
     * <p>Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations
     * can be parallelized without requiring additional synchronization.
     *
     * <p>This is a <a href="package-summary.html#StreamOps">terminal
     * operation</a>.
     *
     * @apiNote There are many existing classes in the JDK whose signatures are
     * well-suited for use with method references as arguments to {@code collect()}.
     * For example, the following will accumulate strings into an {@code ArrayList}:
     * <pre>{@code
     *     List<String> asList = stringStream.collect(ArrayList::new, ArrayList::add,
     *                                                ArrayList::addAll);
     * }</pre>
     *
     * <p>The following will take a stream of strings and concatenates them into a
     * single string:
     * <pre>{@code
     *     String concat = stringStream.collect(StringBuilder::new, StringBuilder::append,
     *                                          StringBuilder::append)
     *                                 .toString();
     * }</pre>
     *
     * @param <R> type of the result
     * @param supplier a function that creates a new result container. For a
     *                 parallel execution, this function may be called
     *                 multiple times and must return a fresh value each time.
     * @param accumulator an <a href="package-summary.html#Associativity">associative</a>,
     *                    <a href="package-summary.html#NonInterference">non-interfering</a>,
     *                    <a href="package-summary.html#Statelessness">stateless</a>
     *                    function for incorporating an additional element into a result
     * @param combiner an <a href="package-summary.html#Associativity">associative</a>,
     *                    <a href="package-summary.html#NonInterference">non-interfering</a>,
     *                    <a href="package-summary.html#Statelessness">stateless</a>
     *                    function for combining two values, which must be
     *                    compatible with the accumulator function
     * @return the result of the reduction
     */
    <R> R collect(Supplier<R> supplier,
                  BiConsumer<R, ? super T> accumulator,
                  BiConsumer<R, R> combiner);

    /**
     * Performs a <a href="package-summary.html#MutableReduction">mutable
     * reduction</a> operation on the elements of this stream using a
     * {@code Collector}.  A {@code Collector}
     * encapsulates the functions used as arguments to
     * {@link #collect(Supplier, BiConsumer, BiConsumer)}, allowing for reuse of
     * collection strategies and composition of collect operations such as
     * multiple-level grouping or partitioning.
     *
     * <p>If the stream is parallel, and the {@code Collector}
     * is {@link Collector.Characteristics#CONCURRENT concurrent}, and
     * either the stream is unordered or the collector is
     * {@link Collector.Characteristics#UNORDERED unordered},
     * then a concurrent reduction will be performed (see {@link Collector} for
     * details on concurrent reduction.)
     *
     * <p>This is a <a href="package-summary.html#StreamOps">terminal
     * operation</a>.
     *
     * <p>When executed in parallel, multiple intermediate results may be
     * instantiated, populated, and merged so as to maintain isolation of
     * mutable data structures.  Therefore, even when executed in parallel
     * with non-thread-safe data structures (such as {@code ArrayList}), no
     * additional synchronization is needed for a parallel reduction.
     *
     * @apiNote
     * The following will accumulate strings into an ArrayList:
     * <pre>{@code
     *     List<String> asList = stringStream.collect(Collectors.toList());
     * }</pre>
     *
     * <p>The following will classify {@code Person} objects by city:
     * <pre>{@code
     *     Map<String, List<Person>> peopleByCity
     *         = personStream.collect(Collectors.groupingBy(Person::getCity));
     * }</pre>
     *
     * <p>The following will classify {@code Person} objects by state and city,
     * cascading two {@code Collector}s together:
     * <pre>{@code
     *     Map<String, Map<String, List<Person>>> peopleByStateAndCity
     *         = personStream.collect(Collectors.groupingBy(Person::getState,
     *                                                      Collectors.groupingBy(Person::getCity)));
     * }</pre>
     *
     * @param <R> the type of the result
     * @param <A> the intermediate accumulation type of the {@code Collector}
     * @param collector the {@code Collector} describing the reduction
     * @return the result of the reduction
     * @see #collect(Supplier, BiConsumer, BiConsumer)
     * @see Collectors
     */
    <R, A> R collect(Collector<? super T, A, R> collector);


    /**
     * 根据提供的Comparator返回此流的最小元素。 这是一个reduction的特例 。
     * @param comparator  一个 non-interfering ， stateless Comparator比较该流的元素
     * @return 一个 Optional此流的最小元素的 Optional如果流为空， Optional
     * @throws NullPointerException  如果最小元素为空
     */
    Optional<T> min(Comparator<? super T> comparator);

    /**
     * 根据提供的Comparator返回此流的最大元素。 这是一个reduction的特殊情况。
     * @param comparator 一个 non-interfering ， stateless Comparator比较该流的元素
     * @return 一个 Optional此流的最大元素的 Optional如果流为空， Optional
     * @throws NullPointerException 如果最大元素为空
     */
    Optional<T> max(Comparator<? super T> comparator);

    /**
     * 返回此流中的元素数
     * @return 这个流中元素的数量
     */
    long count();


    /**
     * Returns whether any elements of this stream match the provided
     * predicate.  May not evaluate the predicate on all elements if not
     * necessary for determining the result.  If the stream is empty then
     * {@code false} is returned and the predicate is not evaluated.
     *
     * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
     * terminal operation</a>.
     *
     * @apiNote
     * This method evaluates the <em>existential quantification</em> of the
     * predicate over the elements of the stream (for some x P(x)).
     *
     * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
     *                  <a href="package-summary.html#Statelessness">stateless</a>
     *                  predicate to apply to elements of this stream
     * @return {@code true} if any elements of the stream match the provided
     * predicate, otherwise {@code false}
     */
    boolean anyMatch(Predicate<? super T> predicate);

    /**
     * Returns whether all elements of this stream match the provided predicate.
     * May not evaluate the predicate on all elements if not necessary for
     * determining the result.  If the stream is empty then {@code true} is
     * returned and the predicate is not evaluated.
     *
     * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
     * terminal operation</a>.
     *
     * @apiNote
     * This method evaluates the <em>universal quantification</em> of the
     * predicate over the elements of the stream (for all x P(x)).  If the
     * stream is empty, the quantification is said to be <em>vacuously
     * satisfied</em> and is always {@code true} (regardless of P(x)).
     *
     * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
     *                  <a href="package-summary.html#Statelessness">stateless</a>
     *                  predicate to apply to elements of this stream
     * @return {@code true} if either all elements of the stream match the
     * provided predicate or the stream is empty, otherwise {@code false}
     */
    boolean allMatch(Predicate<? super T> predicate);

    /**
     * Returns whether no elements of this stream match the provided predicate.
     * May not evaluate the predicate on all elements if not necessary for
     * determining the result.  If the stream is empty then {@code true} is
     * returned and the predicate is not evaluated.
     *
     * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
     * terminal operation</a>.
     *
     * @apiNote
     * This method evaluates the <em>universal quantification</em> of the
     * negated predicate over the elements of the stream (for all x ~P(x)).  If
     * the stream is empty, the quantification is said to be vacuously satisfied
     * and is always {@code true}, regardless of P(x).
     *
     * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
     *                  <a href="package-summary.html#Statelessness">stateless</a>
     *                  predicate to apply to elements of this stream
     * @return {@code true} if either no elements of the stream match the
     * provided predicate or the stream is empty, otherwise {@code false}
     */
    boolean noneMatch(Predicate<? super T> predicate);


    /**
     * 返回描述此流的第一个元素的Optional如果流为空，则返回一个空的Optional
     * 如果流没有遇到顺序，则可能会返回任何元素。
     * @return 一个 Optional此流的第一个元素的 Optional如果流为空， Optional
     * @throws NullPointerException 如果选择的元素为空
     */
    Optional<T> findFirst();

    /**
     * 返回描述流的一些元素的Optional如果流为空，则返回一个空的Optional 。
     * 这个操作的行为显然是不确定的; 可以自由选择流中的任何元素。
     * 这是为了允许并行操作中的最大性能; 成本是同一来源上的多次调用可能不会返回相同的结果。 （如果需要稳定的结果，请改用findFirst() ）
     * @return 一个 Optional此流的某些元素的 Optional如果流为空， Optional
     * @throws NullPointerException  如果选择的元素为空
     * @see #findFirst()
     */
    Optional<T> findAny();


    // Static factories

    /**
     * 返回一个 Stream的生成器。
     */
    public static<T> Builder<T> builder() {
        return new Streams.StreamBuilderImpl<>();
    }

    /**
     * 返回一个空的顺序 Stream 。
     */
    public static<T> Stream<T> empty() {
        return StreamSupport.stream(Spliterators.<T>emptySpliterator(), false);
    }

    /**
     * 返回包含单个元素的顺序 Stream 。
     */
    public static<T> Stream<T> of(T t) {
        return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
    }

    /**
     * 返回其元素是指定值的顺序排序流。
     */
    @SafeVarargs
    @SuppressWarnings("varargs") // Creating a stream from an array is safe
    public static<T> Stream<T> of(T... values) {
        return Arrays.stream(values);
    }

    /**
     * 返回有序无限连续Stream由函数的迭代应用产生f至初始元素seed ，产生Stream包括seed ， f(seed) ， f(f(seed)) ，等
     */
    public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f) {
        Objects.requireNonNull(f);
        final Iterator<T> iterator = new Iterator<T>() {
            @SuppressWarnings("unchecked")
            T t = (T) Streams.NONE;

            @Override
            public boolean hasNext() {
                return true;
            }

            @Override
            public T next() {
                return t = (t == Streams.NONE) ? seed : f.apply(t);
            }
        };
        return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
                iterator,
                Spliterator.ORDERED | Spliterator.IMMUTABLE), false);
    }

    /**
     * 返回无限顺序无序流，其中每个元素由提供的Supplier 。 这适合于产生恒定流，随机元素流等
     *
     * @param <T> 流元素的类型
     * @param s 所述 Supplier生成的元素的
     * @return 一个新的无限顺序无序 Stream
     */
    public static<T> Stream<T> generate(Supplier<T> s) {
        Objects.requireNonNull(s);
        return StreamSupport.stream(
                new StreamSpliterators.InfiniteSupplyingSpliterator.OfRef<>(Long.MAX_VALUE, s), false);
    }

    /**
     * 创建一个懒惰连接的流，其元素是第一个流的所有元素，后跟第二个流的所有元素。
     * 如果两个输入流都被排序，则生成的流被排序，并且如果任何一个输入流是并行的，则并行。 当结果流关闭时，调用两个输入流的关闭处理程序。
     * @param <T> 流元素的类型
     * @param a 第一个流
     * @param b 第二个流
     * @return 两个输入流的并置
     */
    public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b) {
        Objects.requireNonNull(a);
        Objects.requireNonNull(b);

        @SuppressWarnings("unchecked")
        Spliterator<T> split = new Streams.ConcatSpliterator.OfRef<>(
                (Spliterator<T>) a.spliterator(), (Spliterator<T>) b.spliterator());
        Stream<T> stream = StreamSupport.stream(split, a.isParallel() || b.isParallel());
        return stream.onClose(Streams.composedClose(a, b));
    }


    public interface Builder<T> extends Consumer<T> {

        /**
         * Adds an element to the stream being built.
         *
         * @throws IllegalStateException if the builder has already transitioned to
         * the built state
         */
        @Override
        void accept(T t);

        /**
         * Adds an element to the stream being built.
         *
         * @implSpec
         * The default implementation behaves as if:
         * <pre>{@code
         *     accept(t)
         *     return this;
         * }</pre>
         *
         * @param t the element to add
         * @return {@code this} builder
         * @throws IllegalStateException if the builder has already transitioned to
         * the built state
         */
        default Builder<T> add(T t) {
            accept(t);
            return this;
        }

        /**
         * Builds the stream, transitioning this builder to the built state.
         * An {@code IllegalStateException} is thrown if there are further attempts
         * to operate on the builder after it has entered the built state.
         *
         * @return the built stream
         * @throws IllegalStateException if the builder has already transitioned to
         * the built state
         */
        Stream<T> build();

    }
}
